<template>
  <div>
    <el-button type="primary" @click="openAddDialog">新增用户</el-button>
    <AddUserForm v-model:visible="addDialogVisible" @success="handleAddSuccess" />
    <el-table :data="users">
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column label="角色" prop="role"></el-table-column>
      <el-table-column label="状态" prop="status" >
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" prop="action">
        <template #default="scope">
          <el-button type="primary">编辑</el-button>
          <el-button type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  </template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElButton,ElTable,ElTableColumn,ElTag } from 'element-plus';
import request from '@/utils/request.ts';
import AddUserForm from '@/components/user/AddUserForm.vue';


interface User {
  id: number|undefined;
  username: string;
  email: string;
  role: string;
  status: number|undefined;
}

const users = ref<User[]>([]);
const addDialogVisible = ref(false);

const openAddDialog = () => {
  console.log('openAddDialog');
  addDialogVisible.value = true;
};

const handleAddSuccess = async () => {
  addDialogVisible.value = false;
  // 重新获取用户列表
  try {
    const response = await request.get<User[]>('/users');
    users.value = response;
  } catch (error) {
    console.error('Failed to fetch users:', error);
  }
};

onMounted(async () => {
  try {
    const response = await request.get<User[]>('/users');
    users.value = response;
  } catch (error) {
    console.error('Failed to fetch users:', error);
  }
});
</script>

<style scoped>

</style>